package com.zwd.deep.utils;

import lombok.AllArgsConstructor;
import okhttp3.*;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;
import java.util.Objects;

@Component
@AllArgsConstructor
public class OkHttpUtil {
    private final OkHttpClient client;

    public String get(String url) throws IOException {

        // 构建请求
        Request request = new Request.Builder()
                .url(url)
                .build();
        // 发送请求并获取响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body() != null ? response.body().string() : null;
        }
    }
    // TODO 异步需求
/*    public void getAsync(String url, Callback callback) throws IOException {
        // 构建请求
        Request request = new Request.Builder()
                .url(url)
                .build();
        // 发送请求并获取响应
        client.newCall(request).enqueue(callback);
    }*/


    public String postWithFormParams(String url, Map<String, MultipartFile> params) throws IOException {
        MultipartBody.Builder formDataPart = new MultipartBody.Builder()
                .setType(MultipartBody.FORM);
        for(String key : params.keySet()) {
            MultipartFile file = params.get(key);
            File convFile = new File(Objects.requireNonNull(file.getOriginalFilename()));
            try (FileOutputStream fos = new FileOutputStream(convFile)) {
                fos.write(file.getBytes());
            }
            RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), convFile);

            formDataPart.addFormDataPart("image", file.getName(), fileBody);
        }

        MultipartBody requestBody = formDataPart.build();
        return post(url, requestBody);
    }

    public String postWithJsonParams(String url, String json) throws IOException {
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(json, JSON);
        return post(url, body);
    }

    @Nullable
    private String post(String url, RequestBody formBody) throws IOException {
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)
                .addHeader("Content-Type", "application/json; charset=utf-8")
                .build();

        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }
            return response.body() != null ? response.body().string() : null;
        }
    }
}
